/**
 * JAVACC DEMO 1.0
 */
package com.apache.passport.controller;

import com.apache.action.PlatFromAction;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.redis.JedisSsoUtil;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.passport.common.PassportHelper;
import com.apache.passport.entity.BlackRoster;
import com.apache.passport.service.CacheHelper;
import com.apache.tools.NumberUtils;
import com.apache.tools.StrUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  缓存读取操作类,负责缓存的数据管理
 *
 * @author Hou Dayu 创建时间：2016-1-29
 */
@Controller
@RequestMapping({ "/passport/cache/" })
public class CacheAction extends PlatFromAction<BlackRoster> {

    private CacheManager cacheManager = CacheHelper.getInstance().getCache("loginErrToken");

    private CacheManager userCacheManager = CacheHelper.getInstance().getCache("loginToken");

    private final String CACHE_LIST = getPrefix() + "cache-list";

    private final String CACHE_USER_LIST = getPrefix() + "cache-user-list";

    /**
     * description: 查看当前受限制用户
     *
     * @param request
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping({ "list!data.action" })
    @ResponseBody
    public Object list(HttpServletRequest request, String page, String rows) {
        int count = 0;
        Map<String, Object> mapData = new HashMap<String, Object>();
        List<Object> flightPageList = new ArrayList<Object>();
        int pageInt = NumberUtils.getInt(page, 1);//起始页
        int rowsInt = NumberUtils.getInt(rows, 15);//一页显示条数
        List<String> keys = null;
        if (JedisSsoUtil.getInstance().isRedisCache()) {
            keys = JedisSsoUtil.getInstance().getListForSpaceKey("loginErrToken", 0, 0);
        } else {
            keys = cacheManager.getAllKeys();
        }
        if (!Validator.isEmpty(keys)) {
            count = keys.size();//总条数
        }

        if (count > 0) {
            int pageCount = 0;//总页数
            if (count % rowsInt == 0) {
                pageCount = count / rowsInt;
            } else {
                pageCount = (count / rowsInt) + 1;
            }
            //超过总页数置为最后一页
            if (pageInt > pageCount) {
                pageInt = pageCount;
            }
            int tj1 = ((pageInt - 1) * rowsInt);
            for (int i = tj1; i < count && i < ((pageInt) * rowsInt) && pageInt > 0; i++) {
                String key = keys.get(i);
                Object obj = null;
                if (JedisSsoUtil.getInstance().isRedisCache()) {
                    obj = JedisSsoUtil.getInstance().getCacheObjectByKey(key);
                } else {
                    obj = cacheManager.getCacheCloneByKey(key);
                }
                if (null != obj) {
                    flightPageList.add(JedisSsoUtil.getInstance().getCacheObjectByKey(key));
                }
            }
        }

        mapData.put("total", count);
        mapData.put("rows", flightPageList);
        return mapData;
    }

    /**
     * description:  当前登录用户查看
     *
     * @param request
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping({ "list!userdata.action" })
    @ResponseBody
    public Object userlist(HttpServletRequest request, HttpServletResponse response, String page,
            String rows) {

        int count = 0;
        Map<String, Object> mapData = new HashMap<String, Object>();
        List<Object> flightPageList = new ArrayList<Object>();
        int pageInt = NumberUtils.getInt(page, 1);//起始页
        int rowsInt = NumberUtils.getInt(rows, 15);//一页显示条数
        List<String> keys = null;
        if (JedisSsoUtil.getInstance().isRedisCache()) {
            keys = JedisSsoUtil.getInstance().getListForSpaceKey("loginToken", 0, 0);
        } else {
            keys = userCacheManager.getAllKeys();
        }
        if (!Validator.isEmpty(keys)) {
            count = keys.size();//总条数
        }
        if (count > 0) {
            int pageCount = 0;//总页数
            if (count % rowsInt == 0) {
                pageCount = count / rowsInt;
            } else {
                pageCount = (count / rowsInt) + 1;
            }

            //超过总页数置为最后一页
            if (pageInt > pageCount) {
                pageInt = pageCount;
            }

            int tj1 = ((pageInt - 1) * rowsInt);
            for (int i = tj1; i < count && i < ((pageInt) * rowsInt) && pageInt > 0; i++) {
                String key = keys.get(i);
                Object obj = null;
                if (JedisSsoUtil.getInstance().isRedisCache()) {
                    obj = JedisSsoUtil.getInstance().getCacheObjectByKey(key);
                } else {
                    obj = userCacheManager.getCacheCloneByKey(key);
                }
                if (null != obj) {
                    flightPageList.add(JedisSsoUtil.getInstance().getCacheObjectByKey(key));
                }
            }
        }
        mapData.put("total", count);
        mapData.put("rows", flightPageList);
        return mapData;
    }

    /**
     * TODO 从缓存中删除锁定用户.
     */
    @RequestMapping({ "del.action" })
    @ResponseBody
    public ResultMsg delete(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("F", "操作失败,请重试!");
        try {
            if (StrUtil.isNotNull(id)) {
                boolean flag = false;
                if (JedisSsoUtil.getInstance().isRedisCache()) {
                    flag = JedisSsoUtil.getInstance().removeCacheObject("loginErrToken_" + id);
                    JedisSsoUtil.getInstance().delListInfo("loginErrToken", id);
                } else {
                    flag = cacheManager.removeCacheObject(id);
                }
                if (flag) {
                    rmsg.setFlag("T");
                    rmsg.setMsg("删除成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rmsg;
    }

    /**
     * description:  强制退出登录用户<慎用>
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping({ "del-user.action" })
    @ResponseBody
    public ResultMsg deleteUser(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("F", "操作失败,请重试!");
        try {
            if (StrUtil.isNotNull(id)) {
                String tokenCookie = StrUtil.doNull(PassportHelper.getInstance().getCurrCookie(request),request.getHeader("zuultokenid"));
                if (id.equals(tokenCookie)) {
                    rmsg.setFlag("H");
                    rmsg.setMsg("不能将自己踢出");
                    return rmsg;
                }
                boolean flag = false;
                if (JedisSsoUtil.getInstance().isRedisCache()) {
                    flag = JedisSsoUtil.getInstance().removeCacheObject("loginToken_" + id);
                    JedisSsoUtil.getInstance().delListInfo("loginToken", id);
                } else {
                    flag = userCacheManager.removeCacheObject(id);
                }
                if (flag) {
                    rmsg.setFlag("T");
                    rmsg.setMsg("删除成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rmsg;
    }

    /**
     * description:  强制退出登录用户<慎用>
     *
     * @param request
     * @return
     */
    @RequestMapping({ "del-user-all.action" })
    @ResponseBody
    public ResultMsg deleteUserAll(HttpServletRequest request) {
        ResultMsg rmsg = new ResultMsg("F", "操作失败,请重试!");
        try {
            String tokenCookie = StrUtil.doNull(PassportHelper.getInstance().getCurrCookie(request),request.getHeader("zuultokenid"));
            String myCacheKey = "loginToken_" + tokenCookie;
            List<String> keys = null;
            if (JedisSsoUtil.getInstance().isRedisCache()) {
                keys = JedisSsoUtil.getInstance().getListForSpaceKey("loginToken", 0, 0);
            } else {
                keys = userCacheManager.getAllKeys();
            }
            boolean flag = false;
            if (!Validator.isEmpty(keys)) {
                keys.remove(myCacheKey);
                int count = keys.size();
                for (int i = 0; i < count; i++) {
                    String key = keys.get(i);
                    if (JedisSsoUtil.getInstance().isRedisCache()) {
                        flag = JedisSsoUtil.getInstance().removeCacheObject(key);
                        JedisSsoUtil.getInstance().delListInfo("loginToken", key);
                    } else {
                        flag = userCacheManager.removeCacheObject(key);
                    }
                }
            }
            if (flag) {
                rmsg.setFlag("T");
                rmsg.setMsg("删除成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rmsg;
    }

    /**
     * description: 受限制用户页面跳转
     *
     * @param request
     * @return
     */
    @RequestMapping({ "cache-list.action" })
    public ModelAndView cachelist(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(CACHE_LIST);
        return view;
    }

    @RequestMapping({ "cache-user-list.action" })
    public ModelAndView cacheuserlist(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(CACHE_USER_LIST);
        return view;
    }

    @Override
    protected Object data(HttpServletRequest arg0, String arg1, String arg2) {
        return null;
    }

    @Override
    protected BaseManager<BlackRoster> getBaseManager() {
        return null;
    }

    @Override
    protected String getPrefix() {
        return "/passport/passport-";
    }

}
